#-----------------------------------------------------------------------------
# 库导入
#-----------------------------------------------------------------------------
import numpy as np
import pandas as pd

from parse_definition import args
from functools import partial

import cv2 as cv
import os

#-----------------------------------------------------------------------------
# 参数预处理及默认值
#-----------------------------------------------------------------------------
user_skiprows = 4
if(args.skiprows):
    user_skiprows = args.skiprows
    
user_distance = 3
if(args.distance):
    user_distance = args.distance

user_delimiter = ','
if(args.delimiter):
    user_delimiter = args.delimiter
    
user_image_number = 200
if(args.image_number):
    user_image_number = args.image_number

#-----------------------------------------------------------------------------
# 函数定义
#-----------------------------------------------------------------------------
def init():
    if (args.image_path):
        image_path = args.image
    else:
        image_path = 'image/'
        
    if not os.path.exists(image_path): # 默认配置图像文件路径
        os.makedirs(image_path)
        print(image_path + "图像路径已新建！")

def str_to_int(str_data):
    tmp = str_data
    for i in range(str_data.shape[0]):
        for j in range(str_data.shape[1]):
            try:
                # 1. 将byte转成string
                # 2. 再将string转成16进制的int数据（可能转成numpy.int64 或 python 的int）
                x = int(str(str_data[i,j]),16)
                tmp[i,j] = x
            except:
                print("图像数据存在错误，请检查日志！")
                exit(1)
    return tmp

def data_read(file_path, skiprows):
    try:
        data = pd.read_csv(file_path, skiprows=skiprows, delimiter=args.delimiter, encoding='utf8', header=None, nrows=18)
    except:
        print("日志文件读取失败，请检查日志文件是否存在或格式是否正确！")
        exit(1)
    data = data.dropna(axis=1, how='all')  # 丢掉所有NA
    data = np.array(data)
    data = str_to_int(data)
    return data

def write_to_file(file_path, data, image_counts):
    try: 
        with open(file_path,"wb") as f:
            for i in range(data.shape[0]):
                for j in range(data.shape[1]):
                    # 1. 将所有数据转换成np的int64格式
                    # 2. 再将int64格式转换成int格式
                    x = np.int64(data[i,j]).item()
                    f.write(x.to_bytes(1,'little'))
    except:
        print("raw格式图像 " + str(image_counts) + " 写入文件失败！")
        exit(1)

#-----------------------------------------------------------------------------
# 主入口
#-----------------------------------------------------------------------------
if __name__ == '__main__':
    init()
    for i in range(user_image_number):
        skiprows = user_skiprows + i * (18 + user_distance)
        data = data_read(args.file_name, skiprows,)
        write_to_file('image/'+ str(i) + '.raw', data, i)
        data = np.int64(data)
        cv.imwrite(r'image/' + str(i) + '.bmp', data)
    print("日志解析结束，图像已导出！")
